package com.taotao.common.jackson.trim;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * 字段打码序列化器
 */
@Slf4j
@AllArgsConstructor
@NoArgsConstructor
public class TrimFieldDeserializer extends JsonDeserializer<String> implements ContextualDeserializer {

    private Trim trim;

    @Override
    public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        String value = p.getValueAsString();
        if (null == value) {
            return null;
        }

        return value.trim();
    }


    @Override
    public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty beanProperty) throws JsonMappingException {

//        Class<?> targetClass = ctxt.getContextualType().getRawClass();
        if (beanProperty == null) {
            //为空直接跳过
            return ctxt.findContextualValueDeserializer(beanProperty.getType(), beanProperty);
        }

        Trim anno = beanProperty.getAnnotation(Trim.class);
        if (null == anno) {
            return ctxt.findContextualValueDeserializer(beanProperty.getType(), beanProperty);
        }

        return new TrimFieldDeserializer(anno);
    }


}